package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {
    /**
     * 添加任务
     * @param task
     * @return
     */
    @Override
    public long addTask(Task task) {

        //1.添加任务到数据库
        boolean success = addTaskToDb(task);

        //2.保存任务到redis
        if(success){
            addTaskToCache(task);
        }

        return task.getTaskId();
    }

    @Autowired
    private CacheService cacheService;

    /**
     * 保存任务到redis
     * @param task
     */
    private void addTaskToCache(Task task) {



        String key = task.getTaskType()+"_"+task.getPriority();

        //获取未来5分钟的毫秒值
        Calendar calendar =Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);

        if(task.getExecuteTime() <= System.currentTimeMillis()){
            //2.1 任务的执行时间小于等于当前时间，存储list
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(task));
        }else if(task.getExecuteTime() <= calendar.getTimeInMillis()){
            //2.2 任务的执行时间小于等于预设时间（5分钟），存储zset
            cacheService.zAdd(ScheduleConstants.FUTURE+key, JSON.toJSONString(task),task.getExecuteTime());
        }
    }

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    /**
     * 添加任务到数据库
     * @param task
     */
    private boolean addTaskToDb(Task task) {
        boolean flag = false;
        try {
            //保存任务
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            //设置taskid
            task.setTaskId(taskinfo.getTaskId());

            //保存任务日志
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo,taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        } catch (BeansException e) {
            throw new RuntimeException(e);
        }
        return flag;
    }

    /**
     * 取消任务
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(long taskId) {

        //删除任务和更新任务日志
        Task task = updateDb(taskId,ScheduleConstants.CANCELLED);

        //删除redis中的数据
        if(task!=null){
            removeTaskFromCache(task);
        }

        return false;
    }

    /**
     * 删除redis中的数据
     * @param task
     */
    private void removeTaskFromCache(Task task) {
        String key = task.getTaskType()+"_"+task.getPriority();
        if(task.getExecuteTime() <= System.currentTimeMillis()){
            //2.1 任务的执行时间小于等于当前时间，删除list数据
            cacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSON.toJSONString(task));
        }else {
            //2.2 任务的执行时间小于等于预设时间（5分钟），删除zset
            cacheService.zRemove(ScheduleConstants.FUTURE+key, JSON.toJSONString(task));
        }
    }

    /**
     * 删除任务和更新任务日志
     * @param taskId
     * @param status
     */
    private Task updateDb(long taskId,int status) {
        Task task = null;

        try {
            //删除任务
            taskinfoMapper.deleteById(taskId);

            //更新任务日志
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (BeansException e) {
            throw new RuntimeException(e);
        }
        return task;

    }

    /**
     * 拉取任务
     * @param taskType
     * @param priority
     * @return
     */
    @Override
    public Task poll(int taskType, int priority) {

        Task task = null;

        try {
            String key = taskType+"_"+priority;

            //从list中pop数据
            String task_json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if(StringUtils.isNotBlank(task_json)){
                task = JSON.parseObject(task_json, Task.class);
                //删除任务数据和更新任务日志
                updateDb(task.getTaskId(),ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        return task;
    }

    /**
     * 刷新  从zset中刷新到list中
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh(){

        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);

        if(StringUtils.isNotBlank(token)){
            System.out.println("数据同步了....");

            //获得future的所有的key
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            if(futureKeys != null && futureKeys.size() > 0){
                for (String futureKey : futureKeys) {//future_100_1

                    //获得当下的key
                    String topicKey = ScheduleConstants.TOPIC+futureKey.split(ScheduleConstants.FUTURE)[1];

                    //查询数据  小于等于当前时间
                    Set<String> values = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                    if(values != null && values.size() > 0){
                        //同步list
                        /**
                         * 第一个参数  未来数据的key
                         * 第二个参数  当下数据的key
                         * 第三个参数  需要同步的数据
                         */
                        cacheService.refreshWithPipeline(futureKey,topicKey,values);
                    }
                }
            }
        }

    }

    @Scheduled(cron = "0 */5 * * * ?")
    @PostConstruct   //初始化执行
    public void reloadData(){
        //清理数据  不清理不行   数据是小于等于当前时间的，list
        clear();

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);

        //查询符合条件的数据  条件？===小于等于未来5分钟的所有数据
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().le(Taskinfo::getExecuteTime, calendar.getTime()));
        if(taskinfoList!=null && taskinfoList.size() > 0){
            for (Taskinfo taskinfo : taskinfoList) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToCache(task);
            }
        }
        log.info("任务数据从数据库同步到了redis....");


    }

    /**
     * 清理数据
     */
    private void clear() {
        //获取所有的key
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC+"*");
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");

        cacheService.delete(topicKeys);
        cacheService.delete(futureKeys);
    }
}
